<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="客户">
              <el-select v-model="searchForm.customerId" placeholder="请选择客户" clearable style="width: 200px;">
                <el-option v-for="customer in customerOptions" :key="customer.id" :label="customer.name" :value="customer.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="账单状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px;">
                <el-option label="未支付" value="unpaid" />
                <el-option label="已支付" value="paid" />
                <el-option label="已逾期" value="overdue" />
                <el-option label="已退款" value="refunded" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch" :loading="searchLoading">查询</el-button>
              <el-button @click="resetSearch" :disabled="searchLoading">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <div class="action-bar">
        <div class="action-left">
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0" :loading="batchDeleteLoading">
            <el-icon><Delete /></el-icon> 批量删除 ({{ selectedRows.length }})
          </el-button>
        </div>
      </div>

      <el-table 
        :data="tableData" 
        border 
        v-loading="tableLoading" 
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="billCode" label="账单编号" width="150" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="amount" label="账单金额(元)" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.amount?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="账单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paidTime" label="支付时间" width="160">
          <template #default="{ row }">
            {{ row.paidTime ? formatDateTime(row.paidTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="开票状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.invoiced === 1 ? 'success' : 'info'">
              {{ row.invoiced === 1 ? '已开票' : '未开票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="380">
          <template #default="{ row }">
            <el-button size="small" type="info" @click="handleViewDetail(row)">详情</el-button>
            <el-button size="small" type="primary" @click="handleUpdateStatus(row, 'paid')" v-if="row.status !== 'paid'">标记已支付</el-button>
            <el-button size="small" type="danger" plain @click="handleUpdateStatus(row, 'overdue')" v-if="row.status === 'unpaid'">标记逾期</el-button>
            <el-button size="small" type="warning" @click="handleUpdateStatus(row, 'refunded')" v-if="row.status === 'paid'">标记退款</el-button>
            <el-button size="small" type="success" @click="handleApplyInvoice(row)" v-if="row.invoiced !== 1">申请开票</el-button>
            <el-button size="small" type="primary" plain @click="handleQueryInvoice(row)" v-if="row.invoiced === 1">查看发票</el-button>
            <el-button size="small" type="danger" @click="handleSingleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination" v-model:current-page="pagination.current" :page-size="pagination.size" :total="pagination.total" @current-change="handleCurrentChange" layout="prev, pager, next, total" :disabled="tableLoading" />
    </el-card>



    <!-- 申请开票对话框 -->
    <el-dialog v-model="invoiceDialogVisible" title="申请开具发票" width="700px" :close-on-click-modal="false" class="invoice-dialog">
      <el-form ref="invoiceFormRef" :model="invoiceForm" :rules="invoiceRules" label-width="120px">
        <el-form-item label="账单编号">
          <el-input v-model="invoiceForm.billCode" disabled />
        </el-form-item>
        <el-form-item label="账单金额">
          <el-input v-model="invoiceForm.amount" disabled />
        </el-form-item>
        <el-form-item label="购方名称" prop="buyerName">
          <el-input v-model="invoiceForm.buyerName" placeholder="请输入购方名称" />
        </el-form-item>
        <el-form-item label="购方税号" prop="buyerTaxCode">
          <el-input v-model="invoiceForm.buyerTaxCode" placeholder="请输入购方税号（可选）" />
        </el-form-item>
        <el-form-item label="购方地址电话" prop="buyerAddressPhone">
          <el-input v-model="invoiceForm.buyerAddressPhone" placeholder="请输入购方地址电话（可选）" />
        </el-form-item>
        <el-form-item label="购方银行账号" prop="buyerBankAccount">
          <el-input v-model="invoiceForm.buyerBankAccount" placeholder="请输入购方银行账号（可选）" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="invoiceForm.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品数量(用水量)" prop="quantity">
          <el-input-number 
            v-model="invoiceForm.quantity" 
            :min="0.01" 
            :precision="2" 
            style="width: 100%;" 
            placeholder="自动填入账单总用水量"
          />
          <div class="form-item-tip">此数量对应账单的总用水量，单位为吨</div>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="invoiceForm.unit" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="税率" prop="taxRate">
          <el-input v-model="invoiceForm.taxRate" placeholder="请输入税率" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="invoiceForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="invoiceDialogVisible = false" :disabled="invoiceSubmitLoading">取消</el-button>
          <el-button type="primary" @click="submitInvoice" :loading="invoiceSubmitLoading" :disabled="invoiceSubmitLoading">申请开票</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发票详情对话框 -->
    <el-dialog v-model="invoiceDetailDialogVisible" title="发票详情" width="900px" :close-on-click-modal="false">
      <div v-if="invoiceDetail" class="invoice-detail-container">
        <!-- 发票基本信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>发票基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="发票代码">
                  <el-tag type="primary" size="small">{{ invoiceDetail.invoiceCode || '-' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="发票号码">
                  <el-tag type="success" size="small">{{ invoiceDetail.invoiceNumber || '-' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="校验码">{{ invoiceDetail.checkCode || '-' }}</el-descriptions-item>
                <el-descriptions-item label="机器码">{{ invoiceDetail.machineCode || '-' }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="发票日期">
                  <el-tag type="info" size="small">{{ formatDate(invoiceDetail.invoiceDate) || '-' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="发票金额">
                  <span class="amount-highlight">¥{{ invoiceDetail.amountInFiguers || '0.00' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="金额大写">{{ invoiceDetail.amountInWords || '-' }}</el-descriptions-item>
                <el-descriptions-item label="发票状态">
                  <el-tag :type="getInvoiceStatusType(invoiceDetail.status)" size="small">
                    {{ invoiceDetail.status || '未知' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 购方信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>购方信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="购方名称">
              <span class="company-name">{{ invoiceDetail.buyerName || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="购方税号">{{ invoiceDetail.buyerTaxCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="购方地址电话" :span="2">{{ invoiceDetail.buyerAddressPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="购方银行账号" :span="2">{{ invoiceDetail.buyerBankAccount || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 销方信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><OfficeBuilding /></el-icon>
              <span>销方信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="销方名称">
              <span class="company-name">{{ invoiceDetail.sellerName || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="销方税号">{{ invoiceDetail.sellerTaxCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="销方地址电话" :span="2">{{ invoiceDetail.sellerAddressPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="销方银行账号" :span="2">{{ invoiceDetail.sellerBankAccount || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 发票图片 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Picture /></el-icon>
              <span>发票图片</span>
            </div>
          </template>
          <div v-if="invoiceDetail.invoiceUrl" class="invoice-images-container">
            <div class="image-grid">
              <div 
                v-for="(url, index) in invoiceDetail.invoiceUrl.split(',')" 
                :key="index"
                class="image-item"
              >
                <el-image 
                  :src="url.trim()" 
                  :preview-src-list="invoiceDetail.invoiceUrl.split(',').map(u => u.trim())"
                  :initial-index="index"
                  fit="contain"
                  class="invoice-image"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div class="image-label">图片 {{ index + 1 }}</div>
              </div>
            </div>
          </div>
          <div v-else class="no-image">
            <el-empty description="暂无发票图片" :image-size="80">
              <el-button type="primary" @click="invoiceDetailDialogVisible = false">关闭</el-button>
            </el-empty>
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="downloadInvoice" :loading="downloadLoading">
            <el-icon><Download /></el-icon>
            下载发票
          </el-button>
          <el-button type="success" @click="printInvoice">
            <el-icon><Printer /></el-icon>
            打印发票
          </el-button>
          <el-button @click="invoiceDetailDialogVisible = false">关闭</el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="invoiceDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 账单详情对话框 -->
    <el-dialog v-model="billDetailDialogVisible" title="账单详情" width="1000px" :close-on-click-modal="false">
      <div v-if="billDetail" class="bill-detail-container">
        <!-- 账单基本信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>账单基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="账单编号">
                  <el-tag type="primary" size="small">{{ billDetail.billCode || '-' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="账单金额">
                  <span class="amount-text">¥{{ billDetail.amount?.toFixed(2) || '0.00' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="账单状态">
                  <el-tag :type="getStatusType(billDetail.status)">
                    {{ billDetail.statusText || getStatusText(billDetail.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="计费周期">{{ billDetail.billingPeriod || '-' }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="创建时间">{{ formatDateTime(billDetail.createdAt) }}</el-descriptions-item>
                <el-descriptions-item label="支付时间">{{ billDetail.paidTime ? formatDateTime(billDetail.paidTime) : '-' }}</el-descriptions-item>
                <el-descriptions-item label="开票状态">
                  <el-tag :type="billDetail.invoiced === 1 ? 'success' : 'info'">
                    {{ billDetail.invoicedText || (billDetail.invoiced === 1 ? '已开票' : '未开票') }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(billDetail.updatedAt) }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 客户信息 -->
        <el-card class="detail-card" shadow="hover" v-if="billDetail.customer">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>客户信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="客户名称">
              <span class="company-name">{{ billDetail.customer.name || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="统一社会信用代码">{{ billDetail.customer.creditCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ billDetail.customer.contact || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ billDetail.customer.contactPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="账号状态">
              <el-tag :type="billDetail.customer.status === 'active' ? 'success' : 'warning'">
                {{ billDetail.customer.status === 'active' ? '正常' : '停用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(billDetail.customer.createdAt) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 账单明细 -->
        <el-card class="detail-card" shadow="hover" v-if="billDetail.billDetails && billDetail.billDetails.length > 0">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>账单明细</span>
            </div>
          </template>
          <el-table :data="billDetail.billDetails" border size="small">
            <el-table-column prop="deviceId" label="设备ID" width="100" />
            <el-table-column prop="areaId" label="区域ID" width="100" />
            <el-table-column prop="siteId" label="站点ID" width="100" />
            <el-table-column prop="usageAmount" label="用水量(吨)" width="120">
              <template #default="{ row }">
                {{ row.usageAmount?.toFixed(2) || '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计金额" width="120">
              <template #default="{ row }">
                ¥{{ row.subtotal?.toFixed(2) || '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="billingPeriod" label="计费周期" width="120" />
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 设备信息 -->
        <el-card class="detail-card" shadow="hover" v-if="billDetail.devices && billDetail.devices.length > 0">
          <template #header>
            <div class="card-header">
              <el-icon><OfficeBuilding /></el-icon>
              <span>关联设备信息</span>
            </div>
          </template>
          <el-table :data="billDetail.devices" border size="small">
            <el-table-column prop="id" label="设备ID" width="100" />
            <el-table-column prop="model" label="设备型号" width="120" />
            <el-table-column prop="serialNo" label="序列号" width="150" />
            <el-table-column prop="status" label="在线状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'online' ? 'success' : 'warning'">
                  {{ row.status === 'online' ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentMeterReading" label="当前读数(吨)" width="120">
              <template #default="{ row }">
                {{ row.currentMeterReading?.toFixed(2) || '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="lastMeterReading" label="上次读数(吨)" width="120">
              <template #default="{ row }">
                {{ row.lastMeterReading?.toFixed(2) || '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="lastReadingTime" label="上次抄表时间" width="160">
              <template #default="{ row }">
                {{ row.lastReadingTime ? formatDateTime(row.lastReadingTime) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 汇总信息 -->
        <el-card class="detail-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>汇总信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="summary-item">
                <div class="summary-label">总用水量</div>
                <div class="summary-value">{{ billDetail.totalUsageAmount?.toFixed(2) || '0.00' }} 吨</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <div class="summary-label">账单金额</div>
                <div class="summary-value">¥{{ billDetail.amount?.toFixed(2) || '0.00' }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <div class="summary-label">明细数量</div>
                <div class="summary-value">{{ billDetail.billDetails?.length || 0 }} 条</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="billDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Document, User, OfficeBuilding, Picture, Download, Printer } from '@element-plus/icons-vue';
import BillAPI from '@/api/system/bill.api';
import CustomerAPI from '@/api/system/customer.api';
import InvoiceAPI from '@/api/system/invoice.api';
import { formatDate, formatDateTime } from '@/utils/date';

// 搜索表单
const searchForm = reactive({
  customerId: null,
  status: '',
});

// 客户选项
const customerOptions = ref([]);

// 表格数据及状态
const tableData = ref([]);
const tableLoading = ref(false);
const searchLoading = ref(false);

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});



// 发票相关
const invoiceDialogVisible = ref(false);
const invoiceFormRef = ref();
const invoiceSubmitLoading = ref(false);
const invoiceForm = reactive({
  billCode: '',
  amount: '',
  buyerName: '',
  buyerTaxCode: '',
  buyerAddressPhone: '',
  buyerBankAccount: '',
  goodsName: '水费',
  quantity: 1,
  unit: '吨',
  taxRate: '0.06',
  remark: '',
});

// 发票详情相关
const invoiceDetailDialogVisible = ref(false);
const invoiceDetail = ref(null);
const downloadLoading = ref(false);

// 账单详情相关
const billDetailDialogVisible = ref(false);
const billDetail = ref(null);
const billDetailLoading = ref(false);

// 表格选择相关
const selectedRows = ref([]);
const tableRef = ref();
const batchDeleteLoading = ref(false);



// 发票表单验证规则
const invoiceRules = {
  buyerName: [
    { required: true, message: '请输入购方名称', trigger: 'blur' }
  ],
  goodsName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '数量必须大于0.01吨', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入商品单位', trigger: 'blur' }
  ],
  taxRate: [
    { required: true, message: '请输入税率', trigger: 'blur' }
  ]
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'unpaid': 'warning',
    'paid': 'success',
    'overdue': 'danger',
    'refunded': 'info'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'unpaid': '未支付',
    'paid': '已支付',
    'overdue': '已逾期',
    'refunded': '已退款'
  };
  return statusMap[status] || '未知';
};

// 获取发票状态类型
const getInvoiceStatusType = (status) => {
  const statusMap = {
    '正常': 'success',
    '作废': 'danger',
    '红冲': 'warning',
    '未知': 'info'
  };
  return statusMap[status] || 'info';
};

// 加载客户列表
const loadCustomers = async () => {
  try {
    const res = await CustomerAPI.getPage({ currentPage: 1, pageSize: 1000 });
    
    if (res && res.records) {
      customerOptions.value = res.records;
    } else if (res && Array.isArray(res)) {
      customerOptions.value = res;
    } else if (res && res.code === 200 && res.data && res.data.records) {
      // 处理后端Result格式
      customerOptions.value = res.data.records;
    } else {
      customerOptions.value = [];
    }
  } catch (error) {
    console.error('加载客户列表失败:', error);
    customerOptions.value = [];
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.customerId = null;
  searchForm.status = '';
  pagination.current = 1;
  loadBills();
};

// 触发搜索
const onSearch = async () => {
  searchLoading.value = true;
  pagination.current = 1;
  await loadBills();
  searchLoading.value = false;
};

// 加载账单列表
const loadBills = async () => {
  tableLoading.value = true;
  try {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.size,
      customerId: searchForm.customerId || undefined,
      status: searchForm.status || undefined,
    };
    
    const res = await BillAPI.getPage(params);
    
    // 处理不同的响应格式
    if (res && res.records) {
      tableData.value = res.records;
      pagination.total = res.total || 0;
    } else if (res && Array.isArray(res)) {
      tableData.value = res;
      pagination.total = res.length;
    } else if (res && res.data && res.data.records) {
      // 处理嵌套的data结构
      tableData.value = res.data.records;
      pagination.total = res.data.total || 0;
    } else if (res && res.code === 200 && res.data && res.data.records) {
      // 处理后端Result格式
      tableData.value = res.data.records;
      pagination.total = res.data.total || 0;
    } else {
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    ElMessage.error('加载账单列表失败: ' + (error.message || error));
    console.error('账单加载错误:', error);
    tableData.value = [];
    pagination.total = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 分页切换
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadBills();
};

// 表格选择变化处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 单个删除账单
const handleSingleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除账单 ${row.billCode} 吗？\n\n删除后无法恢复，请谨慎操作！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    );
    
    console.log('开始删除账单，ID:', row.id, '账单编号:', row.billCode);
    console.log('请求URL:', `/admin/bill/${row.id}`);
    
    await BillAPI.delete(row.id);
    ElMessage.success('账单删除成功');
    loadBills();
    // 清空选择
    selectedRows.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除账单详细错误:', error);
      console.error('错误响应:', error.response);
      ElMessage.error('删除账单失败: ' + (error.message || error));
    }
  }
};



// 批量删除账单
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的账单');
    return;
  }
  
  try {
    const billCodes = selectedRows.value.map(row => row.billCode).join('、');
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedRows.value.length} 条账单吗？\n\n${billCodes}\n\n删除后无法恢复，请谨慎操作！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    );
    
    batchDeleteLoading.value = true;
    
    // 使用批量删除接口
    const billIds = selectedRows.value.map(row => row.id);
    console.log('开始批量删除账单，ID列表:', billIds);
    console.log('请求URL:', `/admin/bill/batch`);
    
    await BillAPI.deleteBatch(billIds);
    
    ElMessage.success(`成功删除 ${selectedRows.value.length} 条账单`);
    loadBills();
    // 清空选择
    selectedRows.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除详细错误:', error);
      console.error('错误响应:', error.response);
      ElMessage.error('批量删除失败: ' + (error.message || error));
    }
  } finally {
    batchDeleteLoading.value = false;
  }
};

// 更新账单状态
const handleUpdateStatus = async (row, status) => {
  const statusText = getStatusText(status);
  try {
    await ElMessageBox.confirm(`确定要将账单状态更新为"${statusText}"吗？`, '状态更新确认', { type: 'warning' });
    
    await BillAPI.updateStatus(row.id, status);
    ElMessage.success('状态更新成功');
    loadBills();
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('状态更新失败');
      console.error(err);
    }
  }
};

// 申请开票
const handleApplyInvoice = async (row) => {
  try {
    // 根据账单状态显示不同的确认信息
    let confirmMessage = `确定要为账单 ${row.billCode} 申请开具发票吗？`;
    if (row.status === 'unpaid') {
      confirmMessage = `账单 ${row.billCode} 状态为未支付，确定要申请开具发票吗？\n\n注意：未支付账单也可以申请开票，但建议先标记为已支付。`;
    }
    
    // 先确认是否要开发票
    await ElMessageBox.confirm(
      confirmMessage,
      '申请开票确认',
      {
        confirmButtonText: '确定开票',
        cancelButtonText: '取消',
        type: row.status === 'unpaid' ? 'warning' : 'info'
      }
    );

    // 获取完整的账单信息
    const billRes = await BillAPI.findByBillCode(row.billCode);
    console.log('账单查询响应:', billRes);
    
    if (billRes && billRes.billCode) {
      const bill = billRes;
      console.log('账单详细信息:', bill);
      
      // 获取客户信息，自动填入发票信息
      const customerRes = await CustomerAPI.getPage({ 
        currentPage: 1, 
        pageSize: 1000 
      });
      
      let customer = null;
      // 修复：正确处理客户API响应格式
      if (customerRes && customerRes.records && Array.isArray(customerRes.records)) {
        customer = customerRes.records.find(c => c.id === row.customerId);
        console.log('找到的客户信息:', customer);
      }
      
      // 填充发票表单
      invoiceForm.billCode = bill.billCode;
      invoiceForm.amount = `¥${bill.amount?.toFixed(2) || '0.00'}`;
      invoiceForm.buyerName = row.customerName || customer?.name || '';
      invoiceForm.buyerTaxCode = customer?.creditCode || ''; // 使用客户的统一社会信用代码
      invoiceForm.buyerAddressPhone = customer?.contactPhone || ''; // 使用客户的联系电话
      invoiceForm.buyerBankAccount = '';
      invoiceForm.goodsName = '水费';
      
      // 计算总用水量：优先使用bill.totalUsageAmount，如果没有则从billDetails计算
      let totalUsageAmount = 0;
      if (bill.totalUsageAmount && bill.totalUsageAmount > 0) {
        totalUsageAmount = bill.totalUsageAmount;
      } else if (bill.billDetails && Array.isArray(bill.billDetails)) {
        totalUsageAmount = bill.billDetails.reduce((sum, detail) => {
          return sum + (detail.usageAmount || 0);
        }, 0);
      }
      
      // 将商品数量与账单总用水量关联
      invoiceForm.quantity = totalUsageAmount > 0 ? totalUsageAmount : 1;
      invoiceForm.unit = '吨';
      invoiceForm.taxRate = '0.06';
      // 在备注中显示用水量信息
      invoiceForm.remark = `账单总用水量：${totalUsageAmount.toFixed(2)}吨`;
      
      invoiceDialogVisible.value = true;
    } else {
      console.error('账单查询失败:', billRes);
      ElMessage.error('获取账单信息失败: 账单数据格式不正确');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('获取账单信息失败: ' + error.message);
    }
  }
};

// 提交发票申请
const submitInvoice = async () => {
  if (!invoiceFormRef.value) return;
  
  // 立即设置加载状态，防止重复点击
  invoiceSubmitLoading.value = true;
  
  try {
    await invoiceFormRef.value.validate();
    
    const invoiceData = {
      billCode: invoiceForm.billCode,
      buyerName: invoiceForm.buyerName,
      buyerTaxCode: invoiceForm.buyerTaxCode,
      buyerAddressPhone: invoiceForm.buyerAddressPhone,
      buyerBankAccount: invoiceForm.buyerBankAccount,
      goodsName: invoiceForm.goodsName,
      quantity: invoiceForm.quantity.toString(),
      unit: invoiceForm.unit,
      taxRate: invoiceForm.taxRate,
      remark: invoiceForm.remark,
    };
    
    const res = await InvoiceAPI.applyInvoice(invoiceData);
    console.log('发票申请响应:', res);
    
    // 由于请求拦截器已经处理了响应，这里直接判断是否有数据返回
    if (res && (res.invoiceCode || res.billCode)) {
      ElMessage.success('发票申请成功！');
      invoiceDialogVisible.value = false;
      loadBills(); // 重新加载账单列表以更新开票状态
    } else {
      // 显示具体的错误信息
      const errorMessage = res?.message || '申请失败，请稍后重试';
      ElMessage.error(`发票申请失败：${errorMessage}`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 处理不同类型的错误
      let errorMessage = '申请失败，请稍后重试';
      
      if (error.response && error.response.data) {
        const responseData = error.response.data;
        if (responseData.message) {
          errorMessage = responseData.message;
        } else if (responseData.msg) {
          errorMessage = responseData.msg;
        }
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      ElMessage.error(`发票申请失败：${errorMessage}`);
    }
  } finally {
    // 延迟重置加载状态，给用户更好的视觉反馈
    setTimeout(() => {
      invoiceSubmitLoading.value = false;
    }, 500);
  }
};

// 查询发票详情
const handleQueryInvoice = async (row) => {
  try {
    console.log('开始查询发票，账单信息:', row);
    
    const res = await InvoiceAPI.queryInvoice({
      billCode: row.billCode
    });
    
    console.log('发票查询响应:', res);
    
    // 由于请求拦截器已经处理了响应，这里直接判断是否有发票数据
    if (res && (res.invoiceCode || res.billCode)) {
      invoiceDetail.value = res;
      invoiceDetailDialogVisible.value = true;
    } else {
      // 检查是否是发票不存在的错误，提供更友好的提示
      if (res?.message && (res.message.includes('发票不存在') || res.message.includes('账单不存在'))) {
        ElMessage.warning('发票不存在，建议重新申请开具发票。');
        // 重新加载账单列表以更新状态
        loadBills();
      } else {
        ElMessage.error('查询发票失败: ' + (res?.message || '未知错误'));
      }
    }
  } catch (error) {
    console.error('查询发票异常:', error);
    ElMessage.error('查询发票失败: ' + (error.message || error));
  }
};

// 查看账单详情
const handleViewDetail = async (row) => {
  try {
    billDetailLoading.value = true;
    console.log('开始查询账单详情，账单信息:', row);
    
    const res = await BillAPI.getDetailById(row.id);
    console.log('账单详情查询响应:', res);
    
    if (res) {
      billDetail.value = res;
      billDetailDialogVisible.value = true;
    } else {
      ElMessage.error('获取账单详情失败: 未知错误');
    }
  } catch (error) {
    console.error('查询账单详情异常:', error);
    ElMessage.error('获取账单详情失败: ' + (error.message || error));
  } finally {
    billDetailLoading.value = false;
  }
};

// 下载发票
const downloadInvoice = async () => {
  if (!invoiceDetail.value) return;
  
  downloadLoading.value = true;
  try {
    // 这里可以调用下载API
    ElMessage.success('发票下载功能开发中...');
  } catch (error) {
    ElMessage.error('下载失败: ' + (error.message || error));
  } finally {
    downloadLoading.value = false;
  }
};

// 打印发票
const printInvoice = () => {
  if (!invoiceDetail.value) return;
  
  try {
    // 创建打印内容
    const printContent = `
      <div style="font-family: Arial, sans-serif; padding: 20px;">
        <h2 style="text-align: center; color: #333;">发票详情</h2>
        <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
          <tr>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">发票代码</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${invoiceDetail.value.invoiceCode || '-'}</td>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">发票号码</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${invoiceDetail.value.invoiceNumber || '-'}</td>
          </tr>
          <tr>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">发票日期</td>
            <td style="border: 1px solid #ddd; padding: 8px;">${formatDate(invoiceDetail.value.invoiceDate) || '-'}</td>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">发票金额</td>
            <td style="border: 1px solid #ddd; padding: 8px;">¥${invoiceDetail.value.amountInFiguers || '0.00'}</td>
          </tr>
          <tr>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">购方名称</td>
            <td style="border: 1px solid #ddd; padding: 8px;" colspan="3">${invoiceDetail.value.buyerName || '-'}</td>
          </tr>
          <tr>
            <td style="border: 1px solid #ddd; padding: 8px; font-weight: bold;">销方名称</td>
            <td style="border: 1px solid #ddd; padding: 8px;" colspan="3">${invoiceDetail.value.sellerName || '-'}</td>
          </tr>
        </table>
      </div>
    `;
    
    // 创建打印窗口
    const printWindow = window.open('', '_blank');
    printWindow.document.write(printContent);
    printWindow.document.close();
    printWindow.print();
    
    ElMessage.success('打印功能已启动');
  } catch (error) {
    ElMessage.error('打印失败: ' + (error.message || error));
  }
};



// 初始化
onMounted(() => {
  console.log('API基础URL:', import.meta.env.VITE_APP_BASE_API);
  console.log('API目标URL:', import.meta.env.VITE_APP_API_URL);
  loadCustomers();
  loadBills();
});
</script>

<style scoped>
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.card-header {
  padding: 10px 0;
}

.amount-text {
  font-weight: bold;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.invoice-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.no-image {
  text-align: center;
  padding: 20px;
}

/* 发票详情样式 */
.invoice-detail-container {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  font-size: 16px;
  color: #409eff;
}

.amount-highlight {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.company-name {
  font-weight: 600;
  color: #333;
}

.invoice-images-container {
  padding: 10px 0;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  justify-items: center;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.invoice-image {
  width: 200px;
  height: 150px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.invoice-image:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.image-label {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  font-size: 12px;
  gap: 4px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 操作栏样式 */
.action-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格选择列样式 */
.el-table .el-table__cell.is-center {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
  
  .image-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .invoice-image {
    width: 150px;
    height: 112px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}

/* 账单详情样式 */
.bill-detail-container {
  max-height: 70vh;
  overflow-y: auto;
}

.bill-detail-container .detail-card {
  margin-bottom: 20px;
}

.bill-detail-container .detail-card:last-child {
  margin-bottom: 0;
}

.bill-detail-container .card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.bill-detail-container .company-name {
  font-weight: 600;
  color: #409eff;
}

.bill-detail-container .amount-text {
  font-weight: 600;
  color: #67c23a;
  font-size: 16px;
}

.bill-detail-container .summary-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.bill-detail-container .summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.bill-detail-container .summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.bill-detail-container .el-descriptions {
  margin-bottom: 0;
}

.bill-detail-container .el-table {
  margin-top: 10px;
}

/* 表单提示样式 */
.form-item-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 申请开票对话框样式优化 */
.invoice-dialog .el-form-item {
  margin-bottom: 20px;
}

.invoice-dialog .el-input-number {
  width: 100%;
}
</style> 